package com.h3bpm.kumhosunny.wcp.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

/**
 * @Auther: Administrator
 * @Date: 2019/11/28 17:46
 * @Description:
 */

public class RestFulApi {

    public static final String BASE_URL = "http://www.kumhosunny.cn:8989";
    public static final String SECRET = "5F7EDAFB0F59BD687A81D4DCA";
    public static final String ADMIN_USER = "sysadmin";
    public static final String ADMIN_PASS = "ks0812";


    /***
     * 免登陆获取CERTIFICATE
     * @param uname
     * @return
     */
    public static Map<String, String> signNoPass(String uname) {
        Map<String, String> data = new HashMap<>(4);
        data.put("loginname", uname);
        data.put("secret", SECRET);
        data.put("operatorLoginname", ADMIN_USER);
        data.put("operatorPassword", ADMIN_PASS);
        //获取登陆密匙
        JSONObject getLoginObj = httpGet(BASE_URL + "/api/regist/login.do", data);
        String loginCode = getLoginObj.get("CERTIFICATE").toString();

        Map<String, String> resultData = new HashMap<>(4);
        resultData.put("url", BASE_URL + "/home/Pubindex.html?LOGIN_CERTIFICATE=");
        resultData.put("certificate", loginCode);
        return resultData;

    }

    /***
     * 根据bpm工号查询知识库是否存在当前用户
     * @param ucode
     * @return
     */
    public static String searchUser(String ucode) {
        Map<String, String> data = new HashMap<>(4);
        Map<String, String> resultData = new HashMap<>(3);
        data.put("secret", SECRET);
        data.put("loginname", ucode);
        data.put("operatorLoginname", ADMIN_USER);
        data.put("operatorPassword", ADMIN_PASS);

        //获取登陆信息
        JSONObject getLoginObj = httpGet(BASE_URL + "/api/get/user.do", data);
        JSONObject userObject = getLoginObj.getJSONObject("DATA");
        Integer listSize = userObject.getInteger("totalsize");

        if (listSize!=0) {
            return "success";
        } else {
            return "falid";
        }
    }


    /***
     * HTTPGET请求
     * @param url
     * @param data
     * @return
     */
    public static JSONObject httpGet(String url, Map<String, String> data) {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        StringBuilder sb = new StringBuilder();
        sb.append(url);
        JSONObject jsonObject = new JSONObject();

        //传参
        for (String key : data.keySet()) {

            if (sb.toString().indexOf('?') == -1) {
                sb.append("?" + key + "=" + data.get(key));
            } else {
                sb.append("&" + key + "=" + data.get(key));
            }


        }


        HttpGet httpGet = new HttpGet(sb.toString());
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(response.getEntity());
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;

    }


    /***
     * POST请求
     * @param url
     * @param data
     * @return
     */
    public static JSONObject httpPost(String url, Map<String, String> data) {

        long startTime = System.currentTimeMillis();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpPost.setConfig(requestConfig);

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (String key : data.keySet()) {
                params.add(new BasicNameValuePair(key, data.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
            response = httpClient.execute(httpPost, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println(
                        "request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                return JSONObject.parseObject(resultStr);
            }
        } catch (IOException e) {
            if (url.indexOf("info/version") <= 0) {
                System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            }
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                System.out.println("httpPost:" + e + e.getMessage());
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    System.out.println("httpPost:" + e + e.getMessage());
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("httpPost-runtime:" + (endTime - startTime));
        }
        return null;
    }


}




